<%@ Page Language="C#" EnableEventValidation="false" ValidateRequest="false" MasterPageFile="~/Site.master" %>
<%@ Import namespace="SoftwareMonkeys.Scriptech.Scripts" %>
<%@ Import namespace="SoftwareMonkeys.Scriptech.Web" %>
<%@ Import namespace="System.IO" %>
<script runat="server">

	private void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack)
			EditScript(Request.QueryString["Script"]);
	}

	public void EditScript(string script)
	{
		ViewState["OriginalFileName"] = script;
	
		string path = ScriptFileNamer.GetPath(script);
		
		string content = String.Empty;
		
		if (System.IO.File.Exists(path))
		{
			content = ScriptReader.GetContent(script);
		}
		else
		{
			content = ScriptReader.GetTemplate(Path.GetExtension(script));
		}
		
		//Script["Script.NameTaken"] = (Request.QueryString["ScriptNameTaken"] != null && Convert.ToBoolean(Request.QueryString["ScriptNameTaken"]) == true);
		
		ScriptFileName.Text = script;
		
		ScriptContent.Text = content;
		
		if (Request.Form["QueryStrings"] != null && Request.Form["QueryStrings"] != String.Empty)
			QueryStrings.Text = Request.Form["QueryStrings"];
		else
			QueryStrings.Text = PrepareQueryStrings(Request.Url.Query);
		
	}
	
	public string PrepareQueryStrings(string original)
	{
		NameValueCollection data = HttpUtility.ParseQueryString(original);
		
		data.Remove("Script");
		
		string output = String.Empty;
		
		foreach (string key in data.Keys)
		{
			output += key + "=" + data[key] + "&";
		}
		
		output = output.Trim('&');
		
		if (output != String.Empty)
			output = "&" + output;
		
		return output.Trim('&');
	}
		

	private void SaveCloseButton_Click(object sender, EventArgs e)
	{
		Save();
		Close();
	}
	
	private void SaveContinueButton_Click(object sender, EventArgs e)
	{
		Save();
	}
	
	public void Save()
	{
		string originalScriptName = (string)ViewState["OriginalFileName"];
		string newScriptName = ScriptFileName.Text;
		string scriptContent = ScriptContent.Text;
	
		if (ScriptsUtil.SaveScript(originalScriptName, newScriptName, scriptContent))
		{
			Response.Write("Script saved");
			/*if (doPreview == true)
				return Redirect(WebUtilities.MapUrlPath("/Launcher/Preview/" + newScriptName));
			else if (doReturn == true)
				return Redirect(WebUtilities.MapUrlPath("/Scripts/Edit/" + newScriptName));
			else
				return Redirect(WebUtilities.MapUrlPath("/Scripts/Index"));*/
		}
		else
		{
			Response.Write("Save failed");
			//return Redirect(WebUtilities.MapUrlPath("/Scripts/Edit/" + newScriptName + "?ScriptNameTaken=true"));
		}
	}
	
	public void Close()
	{
		string queryStrings = "?" + QueryStrings.Text.Trim('&');
	
		string path = WebUtilities.MapUrlPath("/Scripts/" + ScriptFileName.Text + queryStrings);
	
		Response.Redirect(path);
	}
</script>
<asp:Content ID="BodyContent" ContentPlaceHolderID="Body" runat="server">
<script type="text/javascript">

	function EditCurrentlyPreviewed()
	{
		var previewFrame = document.getElementById("PreviewFrame");
		
		var previewPath = '';
		
		if (previewFrame)
			previewPath = previewFrame.contentWindow.location.href;
		
		var basePath = '<%= WebUtilities.ConvertApplicationRelativeUrlToAbsoluteUrl(WebUtilities.MapUrlPath("/Scripts/")) %>/';
		
		var scriptName = previewPath.replace(basePath, '');
		
		if (scriptName.indexOf("/") == -1)
			Edit(scriptName);
		else
			alert("Cannot detect script name. This page is likely not script based and therefore cannot be edited.");
	}
	
	function Edit(scriptName)
	{
		var url = '/EditScript.aspx?Script=' + scriptName.replace('?', '&');
		
		document.location.href = url;
	}

	function PreparePreview(doPreview)
	{
		//var field = document.getElementById("DoReturn");
		//field.value = doPreview;
		
			
	}
	
	function RenderPreview()
	{
		var scriptPath = '<%= WebUtilities.ConvertApplicationRelativeUrlToAbsoluteUrl("/Scripts/") %>/';
		
		var scriptElement = document.getElementById('<%= ScriptFileName.ClientID %>');
		var queryElement = document.getElementById('<%= QueryStrings.ClientID %>');
		
		var scriptName = '';
		
		if (scriptElement)
			scriptName = scriptElement.value;
			
		var queryString = '';
		
		if (queryElement)
			queryString = "?" + queryElement.value;
			
		/*if (queryString.indexOf("ShowTemplate=") == -1)
		{
			if (queryString.indexOf("?") > -1)
			{
				queryString = queryString + "&";
			}
			else
				queryString = queryString + "?";
				
			queryString = queryString + "ShowTemplate=false";
		}*/
			
		var previewFrame = document.getElementById("PreviewFrame");
				
		scriptPath = scriptPath + scriptName + queryString;
				
		if (previewFrame)
			previewFrame.src = scriptPath;
	}
	
	function PrepareReturn(doReturn)
	{
		//var field = document.getElementById("DoReturn");
		//field.value = doReturn;
	}
	
	function insertTab(o, e)
	{
		var kC = e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which;
		if (kC == 9 && !e.shiftKey && !e.ctrlKey && !e.altKey)
		{
			var oS = o.scrollTop;
			if (o.setSelectionRange)
			{
				var sS = o.selectionStart;
				var sE = o.selectionEnd;
				o.value = o.value.substring(0, sS) + "\t" + o.value.substr(sE);
				o.setSelectionRange(sS + 1, sS + 1);
				o.focus();
			}
			else if (o.createTextRange)
			{
				document.selection.createRange().text = "\t";
				e.returnValue = false;
			}
			o.scrollTop = oS;
			if (e.preventDefault)
			{
				e.preventDefault();
			}
			return false;
		}
		return true;
	}
	
	var isCtrl = false;
	
	document.onkeyup=function(e)
	{
		if(e.which == 17)
			isCtrl=false;
	}
	
	document.onkeydown=function(e)
	{
		if(e.which == 17)
			isCtrl=true;
	
		if(e.which == 83 && isCtrl == true)
		{
			PreparePreview(false);
		
			var btn = document.getElementById('<%= SaveContinueButton.ClientID %>');
			if (btn)
				btn.click();
			return false;
		}
	}
	

</script>
<script type="text/javascript" defer>

	window.onload=function(){
		RenderPreview();
	}

</script>
<h1>Create/Edit Script</h1>
<p><a href='<%= Request.ApplicationPath %>'>Home</a> - <a href='<%= WebUtilities.MapUrlPath("/Scripts.aspx") %>'>Index</a></p>

<p>
	File name: <asp:textbox runat="server" id="ScriptFileName" width="400px"/>
</p>
<p>
	<asp:textbox runat="server" id="ScriptContent" style="width: 100%; height: 400px;" onkeydown="insertTab(this, event);" TextMode="Multiline" wrap="false"/>
</p>
<p>
	Parameters (query string): <asp:textbox runat="server" id="QueryStrings" width="100%"/>
</p>
<p>
	<asp:button runat="server" OnClick="SaveCloseButton_Click" text="&laquo; Save &amp; Close" />&nbsp;<asp:button runat="server" id="SaveContinueButton" OnClick="SaveContinueButton_Click" text="Save & Continue" /> (Hit CTRL+S to save and preview.)
</p>

<hr/>
<h1>Preview</h1>
<div style="text-align: right">
<a href="javascript:EditCurrentlyPreviewed();">Edit this script &raquo;</a>
</div>
<iframe id="PreviewFrame" width="100%" height="800" />
</asp:Content>